package com.rfs.juc;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author renfushuai
 * @date 2022/5/31
 */
public class CASCountTest {
    private static AtomicInteger atomicI=new AtomicInteger(0);
    private static int count=0;

    public static void main(String[] args) throws InterruptedException {
        List<Thread> ts=new ArrayList<>(600);
        long start=System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            Thread t = new Thread(() -> {
                for (int i1 = 0; i1 < 10000; i1++) {
                    unSafeCount();
                    safeCount();
                }
            });
            ts.add(t);
        }
        for (Thread t : ts) {
            t.start();
        }
        for (Thread t : ts) {
            t.join();
        }
        System.out.println("非线程安全："+count);
        System.out.println("线程安全："+atomicI.get());
        System.out.println(System.currentTimeMillis()-start);

    }

    private static void unSafeCount() {
        count++;
    }
    private static void safeCount(){
        for (; ; ) {
            int i=atomicI.get();
            boolean suc=atomicI.compareAndSet(i,++i);
            if (suc) {
                break;
            }
        }
    }
}
